using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Mvc.Filters;
using Chaunce.Web.Core;
using System.Threading.Tasks;
using Chaunce.FrameWork.NetCore.Utility.Exceptions;
using Chaunce.FrameWork.NetCore.SysCore.Consts;
using Chaunce.FrameWork.NetCore.Chaunce.Utility.Helpers;

namespace Chaunce.Web.Core.Filters
{
    /// <summary>
    /// model绑定元数据有效性验证异常
    /// </summary>
    public class ViewModelStateActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                string errorMsg = context.ModelState.ToModelStateError();
                if (string.IsNullOrEmpty(errorMsg))
                {
                    errorMsg = "数据验证失败";
                }
                string bindModelText = context.ModelState.ToBindModelText();
                throw new ViewModelStateValidException(errorMsg, bindModelText,AppErrorCode.ModelInValid.ToInt());
            }
            await next();
        }
    }
}